package com.ruoyi.products.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.config.wx.WeChatUtil;
import com.ruoyi.common.config.wx.pay.WxPayConfig;
import com.ruoyi.common.config.wx.pay.WxPayInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.products.domain.BussCoupons;
import com.ruoyi.products.domain.BussOrder;
import com.ruoyi.products.service.IWxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.token.TokenService;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;


/**
 * 微信支付相关接口
 *
 * @author xsk
 */
@RestController
@RequestMapping("/wx/pay")
@Slf4j
public class WxPayProdController extends BaseController {


    @Autowired
    private IWxPayService iWxPayService;

    //配置微信支付
    @Autowired
    private WxPayConfig wxPayConfig;



    //支付成功修改 会员实际
    @GetMapping("/paySuccess")
    public R paySuccess() {
        iWxPayService.paySuccess(getOpenId());
        return R.ok("支付成功");
    }


    /**
     * 使用getResourceAsStream直接从resources根路径下获取文件流
     *
     * @param path
     */
    private InputStream getFileInputStream(String path) {
        InputStream in = this.getClass().getResourceAsStream(path);
        return in;
    }


    @RepeatSubmit
    @PostMapping("/createOrder")
    public R<WxPayInfo> createOrder(@RequestBody BussCoupons bo) throws IOException {
        BussOrder bussOrder = new BussOrder();
        bussOrder.setOpenId(getOpenId());
        bussOrder.setCouponsId(bo.getId());
        return R.ok(iWxPayService.createOrder(bussOrder));
    }

    /**
     * 支付回调通知处理
     * 放行
     * @param
     * @return
     * @throws
     */
    @Anonymous
    @PostMapping("/notify/order")
    public Map parseOrderNotifyResult(HttpServletRequest servletRequest) {
        return iWxPayService.parseOrderNotifyResult(servletRequest);
    }

    /**
     * 微信退款
     *
     * @param bo
     * @return
     * @throws Exception
     */
//    @PostMapping("/refund")
//    public R refund(@RequestBody StuOrderBo bo) throws Exception {
//        return R.ok("退款成功", iWxPayService.refund(bo));
//    }

    /**
     * 查询 微信支付订单
     *
     * @throws Exception
     */
//    @GetMapping("queryWxOrder/{stuUserId}")
//    public R queryWxOrder(@PathVariable(value = "stuUserId") @NotNull(message = "stuUserId不可为空值") Long stuUserId) throws Exception {
//        return R.ok(iWxPayService.queryWxOrder(stuUserId));
//    }
//
//    /**
//     * 查询 微信支付订单
//     *
//     * @throws Exception
//     */
//    @GetMapping("queryByOrderNo/{orderNo}")
//    public R queryByOrderNo(@PathVariable(value = "orderNo") @NotNull(message = "orderNo") String orderNo) throws Exception {
//        return R.ok(iWxPayService.queryByOrderNo(orderNo));
//    }
//
//    /**
//     * 关闭微信支付订单
//     *
//     * @throws Exception
//     */
//
//    @PostMapping("/closeWxOrder/{stuUserId}")
//    public R CloseWxOrder(@PathVariable(value = "stuUserId") @NotNull(message = "stuUserId 不可为空值") Long stuUserId) throws Exception {
//        return R.ok("关闭成功", iWxPayService.CloseWxOrder(stuUserId));
//    }

    /**
     * 获取openid
     *
     * @param
     */
    @GetMapping(value = "/getOpenid")
    public R<String> login(@NotNull(message = "code不可不空值") String code) {
        // 根据小程序穿过来的code想这个url发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxPayConfig.getAppId() + "&secret=" + wxPayConfig.getAppSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            // 发送请求，返回Json字符串
            String str = WeChatUtil.httpRequest(url, "GET", null);
            // 转成Json对象 获取openid
            JSONObject jsonObject = JSONObject.parseObject(str);
            // 我们需要的openid，在一个小程序中，openid是唯一的
            String openid = jsonObject.get("openid").toString();
            return R.ok("授权成功", openid);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }


    /**
     * 获取小程序跳转地址
     *
     * @param
     */
//    @GetMapping(value = "/getUrl/{stuUserId}")
//    public R getUrl(@PathVariable Long stuUserId) throws Exception {
//        String appletUrl = iWxPayService.getAppletUrl(stuUserId);
//        return R.ok("授权成功", appletUrl);
//    }

    /**
     * 获取微信配置
     *
     * @param
     */
    @GetMapping(value = "/getWxConfig")
    public AjaxResult getWxConfig(@NotNull(message = "stuUserId 不可为空") String stuUserId) throws Exception {
        return AjaxResult.success("授权成功",  iWxPayService.getWxConfig(stuUserId));
    }


//    /**
//     * 退出登录
//     */
//    @PostMapping("/logout")
//    public R<Void> logout() {
//        try {
//            LoginUser loginUser = LoginHelper.getLoginUser();
//            StpUtil.logout();
//        } catch (NotLoginException ignored) {
//        }
//        return R.ok("退出成功");
//    }

}

